package cn.com.zhbs.account.util;

/**
 * @author 陈治杰
 * @Title: TreeRecursion
 * @Description:
 * @date 2019/7/1914:49
 */

import cn.com.zhbs.account.entitys.Node;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.*;

/**
 * @author jack cooper
 * @create 2017-09-15 16:53
 */
public class TreeRecursion {


    /**
     * 递归处理   数据库树结构数据->树形json
     * @param nodeId
     * @param nodes
     * @return
     */
    public static JSONArray getNodeJson(String nodeId, Map<String,Node> nodes){

        //当前层级当前node对象
        Node cur = nodes.get(nodeId);
        //当前层级当前点下的所有子节点（实战中不要慢慢去查,一次加载到集合然后慢慢处理）
        List<Node> childList = getChildNodes(nodeId,nodes);

        JSONArray childTree = new JSONArray();
        for (Node node : childList) {
            JSONObject o = new JSONObject();
            o.put("id", node.getId());
            o.put("name", node.getName());
            o.put("desc", node.getDesc());
            o.put("type", node.getType());
            o.put("order_num", node.getOrder_num());
            JSONArray childs = getNodeJson(node.getId(),nodes);  //递归调用该方法
            if(!childs.isEmpty()) {
                o.put("children",childs);
            }
            childTree.add(o);
        }
        return childTree;
    }

    /**
     * 获取当前节点的所有子节点
     * @param nodeId
     * @param nodes
     * @return
     */
    public static List<Node> getChildNodes(String nodeId, Map<String,Node> nodes){
        List<Node> list = new ArrayList<>();
        for (String key : nodes.keySet() ) {
            if(nodes.get(key).getParentId().equals(nodeId)){
                list.add(nodes.get(key));
            }
        }
        return list;
    }


    public static JSONArray sortList(JSONArray menu) {
        JSONArray jsonArray = new JSONArray();
        List<JSONObject> list = JSONArray.parseArray(menu.toJSONString(), JSONObject.class);
        for(int i=0;i<list.size();i++){
            JSONObject jo=list.get(i);
            if(jo.containsKey("children")){
                JSONArray ja=sortList(JSONArray.parseArray(jo.get("children").toString()));
                jo.put("children",ja);
            }
            jsonArray.add(jo);
        }
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                int a = o1.getInteger("order_num");
                int b = o2.getInteger("order_num");
                if (a > b) {
                    return 1;
                } else if (a == b) {
                    return 0;
                } else
                    return -1;
            }
        });
        return JSONArray.parseArray(list.toString());
    }
}
